﻿using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ServerSidePhysics.Core
{
    public static class StaticHelpers
    {
        public static FileStream fs = null; 

        public static void Log(string msg)
        {
            msg = DateTime.Now.ToLongTimeString() + " >>> " + msg + "\n";
            Console.Write(msg);

            if(fs == null)
            {
                InitLogger();
            }

            fs.Write(Encoding.UTF8.GetBytes(msg + Environment.NewLine), 0, Encoding.UTF8.GetByteCount(msg + Environment.NewLine));
            fs.Flush();
        }

        public static void InitLogger()
        {
            string name = string.Format("./server_log-{0:yyyy-MM-dd_hh-mm}.txt", DateTime.Now);
            if(File.Exists(name))
            {
                File.Delete(name);
            }
            fs = File.OpenWrite(name);
        }

        public static byte[] GetBodyArray(Dictionary<int, Vector2> data)
        {
            List<byte> ids = new List<byte>();
            List<byte> positions = new List<byte>();

            foreach(KeyValuePair<int, Vector2> pair in data)
            {
                byte[] temp = BitConverter.GetBytes(pair.Key);
                ids.AddRange(temp);
                //ids.AddRange(new byte[2] { 0x02, 0x03});

                byte[] v1 = BitConverter.GetBytes(pair.Value.X);
                byte[] v2  = BitConverter.GetBytes(pair.Value.Y);

                positions.AddRange(v1);
                //positions.AddRange(new byte[2] { 0x01, 0x04});
                positions.AddRange(v2);
                //positions.AddRange(new byte[2] { 0x02, 0x03 });
            }

            List<byte> res = new List<byte>();
            res.AddRange(BitConverter.GetBytes((int)data.Count));
            res.AddRange(ids);
            //res.AddRange(new byte[2] { 0x01, 0x04 });
            res.AddRange(positions);

            return res.ToArray<byte>();
        }

        public static void ReleaseAll()
        {
            Networking.ClearNetworking();
            Globals.stopwatch.Stop();
            Globals.stopwatch = null;
        }
    }
}
